import SequenceRouter from '../../../public/js/config/report-entrance.js';
import { getAuthZ, TEST_NUMBER, TEST_INFO_NUMBER, YY_NUMBER, Collaboration_APP, Service_APP } from '../../../public/js/config/config.js';
import WxcodeApi from '../../../public/js/common/api/account/wxcode.api.js';
import { MESSAGE_WAIT_TYPE_001 } from '../../../public/js/common/pointentrance.js';

Utils.NameSpace('SN.H5.Account.WXCode');
(function (window, document, $) {
    $(function () {
        /*JS严格模式*/
        'use strict';
        $('body').attr('data-weui-theme', 'light'); // 强制光明模式
        SN.H5.Account.WXCode.EncodeUrl(); /*url编码*/
        SN.H5.Account.WXCode.PageInit(); /*页面初始化*/
        SN.H5.Account.WXCode.BtnReload(); /*重试按钮*/
        $('#application-date').text(`2019-${new Date().getFullYear()}`);
        $('#application-environment').text('ynsnjt.cn');
    });

    /*页面初始化*/
    SN.H5.Account.WXCode.PageInit = function () {
        let wxCode = Utils.GetQueryString('code');
        let wxState = Utils.GetQueryString('state');
        $('#loadDiv').show();
        $.ajax({
            url: Utils.CurDomain.WeiXinUrl + '/wxauths/code',
            type: 'GET',
            //timeout: 3000,
            async: false,
            data: {
                code: wxCode,
                state: wxState,
            },
            success: function (rebackData) {
                if (rebackData.code == '1Status200') {
                    /*未注册，未建档*/
                    window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx7429f9fc58f35ce5&redirect_uri=https://qas.it.ynsnjt.net/h5it/html/account/register.html&response_type=code&scope=snsapi_userinfo&state=gh_94f4b4e471ab#wechat_redirect`;
                } else {
                    // 正常人员获取jwt，code接口会返给你guid = rebackData.data Utils.CurDomain.SysAuthUrl + '/account/wechat/' + guid,
                    setTimeout(function () {
                        SN.H5.Account.WXCode.GetSNAuthAT(rebackData.data);
                        // 存储openid
                        Utils.SetSessionStorage('openId', rebackData?.data?.openId);
                        Utils.SetSessionStorage('guid', rebackData?.data?.guid);
                    }, 1000);
                }
            },
            error: Utils.AjaxError,
            // error: function(e) {
            // 	loading.hide();
            // 	console.error(e);
            // 	/*SN.H5.Account.WXCode.ShowInfo(e.responseJSON.msg);*/
            // 	if (e.responseJSON == undefined) {
            // 		/** 判断若为其他异常则返回*/
            // 		return;
            // 	} else if (e.responseJSON.code == "2Status400") {
            // 		/*注册了，未建档*/
            // 		window.location.href = 'wait.html?v=' + Utils.GetTime();
            // 	} else {
            // 		SN.H5.Account.WXCode.Tooltips(e.responseJSON.msg);
            // 	}
            // }
        }).fail(function () {
            // loading.hide();
            $('#loadDiv').hide();
        });
    };

    /*截取页面url地址并编码*/
    SN.H5.Account.WXCode.EncodeUrl = function () {
        let url = window.location.href;
        url = url.slice(0, url.indexOf('?'));
        Utils.SetSessionStorage('url', url);
        let wxState = Utils.GetQueryString('state');
        $('#btnRetry').attr('href', Utils.CompleteUrl({ wxid: getAuthZ(wxState, 'id'), url: url, sid: wxState }));
    };

    SN.H5.Account.WXCode.GetSNAuthAT = function (value) {
        $.ajax({
            url: Utils.CurDomain.AccountUrl + '/mpaccounts/jwt/' + value.guid, //获取code关联用户的JWT信息
            type: 'GET',
            success: function (result) {
                if (!Utils.IsNotNull(result)) {
                    //jwt为空，获取登记信息
                    SN.H5.Account.WXCode.GetMPAccounts(value.openId);
                    return;
                }
                let res = JSON.parse(result);
                Utils.SetSNAuthAT(res.AccessToken);
                queryUserName();
                Utils.SetSessionStorage('Sid', Utils.GetQueryString('state'));
                WxcodeApi.getReforguserpi().then((res) => {
                    SN.H5.Account.WXCode.GetACToken();
                });
                SN.H5.Account.WXCode.LoadMenusData();
            },
            error: Utils.AjaxError,
        });
    };

    //获取登记信息
    SN.H5.Account.WXCode.GetMPAccounts = function (openId) {
        $.ajax({
            url: Utils.CurDomain.AccountUrl + `/mpaccounts/register/${Utils.GetQueryString('state')}/${openId}`, //获取code关联用户的JWT信息
            type: 'GET',
            success: function (res) {
                if (Utils.IsNotNull(res)) {
                    //等待页面
                    window.location.href = `../components/wait/wait.html?v=${Utils.GetTime()}&state=${Utils.GetQueryString('state')}&index=2&type=${MESSAGE_WAIT_TYPE_001}&openId=${openId}`;
                } else {
                    //注册页面
                    window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx7429f9fc58f35ce5&redirect_uri=https://qas.it.ynsnjt.net/h5it/html/account/register.html&response_type=code&scope=snsapi_userinfo&state=gh_94f4b4e471ab#wechat_redirect`;
                }
            },
            error: Utils.AjaxError,
        });
    };

    const queryUserName = () => {
        // 获取 JWT信息
        // WxcodeApi.queryUserName().then(res => {
        // 	Utils.SetSessionStorage("SNLoginUserInfo", res);/* 将用户信息缓存到Session中*/
        // })
        let token = Utils.GetSNAuthAT();
        let strings = token.split('.'); //截取token，获取载体
        let userinfo = JSON.parse(decodeURIComponent(escape(window.atob(strings[1].replace(/-/g, '+').replace(/_/g, '/')))));
        Utils.SetSessionStorage('SNLoginUserInfo', userinfo); /* 将用户信息缓存到Session中*/
    };
    SN.H5.Account.WXCode.GetACToken = function () {
        let wxState = Utils.GetQueryString('state');
        if (wxState == Collaboration_APP.sourceID || wxState == TEST_NUMBER.sourceID || wxState == TEST_INFO_NUMBER.sourceID) {
            let _json = Utils.ParsingUrl(window.location);
            let _pathUrl = SequenceRouter.getRouterPath(_json.routerType);
            //let _url = {
            //	[TEST_NUMBER.sourceID]: 'snitmp',
            //	[TEST_INFO_NUMBER.sourceID]: 'sninfomp',
            //}
            if (_pathUrl) {
                return (window.location.href = `../features/${_pathUrl}${Utils.ConverToUrl(_json)}&v=${Utils.GetTime()}`);
            }
            return (window.location.href = `../features/main.html?code=${Utils.GetQueryString('code')}&state=${Utils.GetQueryString('state')}&v=${Utils.GetTime()}`);
        }
        //let _url = {
        //	[Collaboration_APP.sourceID]: 'snitmp',
        //	[Service_APP.sourceID]: 'sninfomp',
        //}
        //$.ajax({
        //    "url": Utils.CurDomain.WeiXinUrl + '/wxauths/basetoken',
        //    "data": {
        //        "SId": Utils.GetQueryString('state'),
        //    },
        //    "type": 'GET',
        //    "datatype": "json",
        //    "beforeSend": _xml,
        //    "success": function (result) {
        //        Utils.SetSessionStorage('AC_token', result.data);
        //        // _userInfo(result.data)

        //        let _json = Utils.ParsingUrl(window.location);
        //        let _pathUrl = SequenceRouter.getRouterPath(_json.routerType);
        //        if (_pathUrl) {
        //            return window.location.href = `../features/${_pathUrl}${Utils.ConverToUrl(_json)}`;
        //        }
        //        window.location.href = `../features/main.html?code=${Utils.GetQueryString('code')}&state=${Utils.GetQueryString('state')}&v=${Utils.GetTime()}`;
        //    },
        //    "error": Utils.AjaxError
        //});
    };
    const _xml = function (XMLHttpRequest, textStatus, errorThrow) {
        let _pathUrl = Utils.ParsingUrl(window.location);
        XMLHttpRequest.setRequestHeader('AuthZ', getAuthZ(_pathUrl.state, 'secret')); //"Bearer " + Utils.GetSNAuthAT()
        XMLHttpRequest.setRequestHeader('Content-Type', 'application/json');
        XMLHttpRequest.setRequestHeader('Accept', 'application/json');
    };

    /*重试按钮*/
    SN.H5.Account.WXCode.BtnReload = function () {
        $('#btnRetry').on('click', function () {
            $(this).addClass('weui-btn_disabled weui-btn_loading');
            $(this).text('加载中...');
            $(this).prepend('<span class="weui-primary-loading"></span>');
            $(this).off('click');
        });

        $('#clear-cache').on('click', function () {
            window.location.href = '../clearcache.html';
        });
    };

    /*错误提示*/
    SN.H5.Account.WXCode.Tooltips = function (msg) {
        let $tooltips = $('#topTips');
        $tooltips.text(msg).fadeIn().delay(1500).fadeOut();
    };

    /* 加载菜单数据信息 */
    SN.H5.Account.WXCode.LoadMenusData = function () {
        $.ajax({
            url: Utils.CurDomain.SysPlfUrl + '/yymenus/o/10' /* 请求地址 */,
            type: 'GET' /* 请求方式 */,
            beforeSend: Utils.AjaxBeforeSend /* 发送请求前 */,
            dataType: 'json' /* 返回数据类型 */,
            success: SN.H5.Account.WXCode.BuildMenus /* 请求: √成功! */,
            error: Utils.AjaxError /* 请求: ×失败! */,
            // complete: Utils.AjaxComplete/* 请求: o完成! */
        });
    };
    /* 菜单数据写入Session */
    SN.H5.Account.WXCode.BuildMenus = function (res) {
        Utils.SetSessionStorage('SNMenus', res.data);
        //window.location.href = `../features/main.html?code=${Utils.GetQueryString('code')}&state=${Utils.GetQueryString('state')}&v=${Utils.GetTime()}`; //等待菜单列表加载完成后在跳转首页，否则会出现第一次菜单点击不了的情况
    };
})(window, document, jQuery);
